<template>
  <div class="cjui-dynamic-form-editor">
    <div class="page-header">
      <el-steps :active="1" finish-status="success" simple class="w-250px">
        <el-step title="基础设置" @click="stepClick(0)" />
        <el-step title="表单设计" @click="stepClick(1)" />
      </el-steps>

      <div>
        <el-button round :disabled="activeStep === 0" @click="prev">上一步</el-button>
        <el-button round :disabled="activeStep === 1" @click="next">下一步</el-button>
        <el-button round type="primary" @click="save">保存</el-button>
        <el-button round @click="cancel">取消</el-button>
      </div>
    </div>

    <div class="page-body">
      <!-- 步骤1：基础设置 -->
      <div v-if="activeStep === 0" class="cjui-dynamic-form-editor-base">
        <component
          :is="components['BaseInfoProperty']"
          v-model="baseInfoComponent.property"
        />
      </div>

      <!-- 步骤2：通用表单 -->
      <div v-if="activeStep === 1" class="cjui-dynamic-form-editor-diy">
        <div class="left-board">
          <EditorLibrary />
        </div>

        <div class="center-board flex flex-col">
          <div class="action-bar">
            <el-link @click="preview" class="mr-10px">预览</el-link>
            <el-link @click="empty">清空</el-link>
          </div>

          <div class="flex-1 overflow-auto">
            <EditorDraw />
          </div>
        </div>

        <div class="right-board">
          <el-tabs v-model="currentTab">
            <el-tab-pane label="组件属性" name="fields">
              <el-scrollbar>
                <component
                  v-if="selectedComponent"
                  :is="components[`${selectedComponent.id}Property`]"
                  :key="selectedComponent?.uid || selectedComponent?.id"
                  v-model="selectedComponent.property"
                />
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="表单属性" name="form">
              <el-scrollbar>
                <component
                  :is="components[`BaseFormProperty`]"
                  v-model="baseFormComponent.property"
                />
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <PreviewDialog v-model:visible="previewDialog.visible" :form-config="previewDialog.formConfig" />
  </div>
</template>

<script lang="ts" setup>
import _ from 'lodash-es'
import { FormConfigSubmit } from './types'
import { FormConfigBuild } from './utils'
import { components, DiyComponent } from './components/index'
import {
  FormConfigBaseInfo,
  component as baseInfoComponentRefer,
} from './components/BaseInfo/config'
import {
  FormConfigBaseForm,
  component as baseFormComponentRefer,
} from './components/BaseForm/config'
import EditorLibrary from './editor-library.vue'
import EditorDraw from './editor-draw.vue'
import PreviewDialog from './preview.vue'

defineOptions({
  name: 'CjuiDynamicFormEditor',
})

const message = useMessage()

type Props = {
  modelValue: FormConfigSubmit
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
})
const emits = defineEmits(['update:modelValue'])

// 基础设置组件
const baseInfoComponent = ref<DiyComponent<FormConfigBaseInfo>>(
  _.cloneDeep(baseInfoComponentRefer),
)
// 表单容器组件
const baseFormComponent = ref<DiyComponent<FormConfigBaseForm>>(
  _.cloneDeep(baseFormComponentRefer),
)
// 组件列表
const pageComponents = ref<DiyComponent<any>[]>([])
// 选中的组件
const selectedComponent = ref<DiyComponent<any>>()
// 选中的组件索引
const selectedComponentIndex = ref<number>(-1)
// 全局下沉属性
provide('baseInfoComponent', baseInfoComponent)
provide('baseFormComponent', baseFormComponent)
provide('pageComponents', pageComponents)
provide('selectedComponent', selectedComponent)
provide('selectedComponentIndex', selectedComponentIndex)

watch(
  () => props.modelValue,
  () => {
    const modelValue = new FormConfigBuild(props.modelValue)
    baseInfoComponent.value.property = modelValue
    baseFormComponent.value.property = modelValue.configJson
    pageComponents.value = modelValue.configJson.fields
    if (pageComponents.value.length) {
      selectedComponent.value = pageComponents.value[0]
      selectedComponentIndex.value = 0
    }
    console.log('moooasdas', modelValue, pageComponents.value)
  },
  { immediate: true, deep: true },
)

// ============ 顶层操作 ==============
// 步骤
const activeStep = ref<number>(1)
function stepClick(step: number) {
  activeStep.value = step
}
function prev() {
  activeStep.value--
}
function next() {
  activeStep.value++
}
// 保存
function save() {
  console.log('xxxxxxxxx', {
    baseInfo: baseInfoComponent.value.property,
    configJson: {
      ...baseFormComponent.value.property,
      fields: [...pageComponents.value],
    },
  })
}
// 取消
function cancel() {}

// ============ 中间看板 ==============
// 预览
const previewDialog = reactive({
  visible: false,
  formConfig: undefined
})
function preview() {
  previewDialog.formConfig = {
    ...baseInfoComponent.value.property,
    configJson: JSON.stringify({
      ...baseFormComponent.value.property,
      fields: [...pageComponents.value],
    })
  }
  previewDialog.visible = true
}
// 清空
async function empty() {
  await message.confirmError('确定要清空所有组件吗？')
  pageComponents.value = []
}

// ============ 右侧看板 ==============
type CurrentTab = 'fields' | 'form'
const currentTab = ref<CurrentTab>('form')
watch(() => selectedComponent.value, (newVal) => {
  if (newVal && currentTab.value === 'form') {
    currentTab.value = 'fields'
  }
})
</script>

<style lang="scss">
.cjui-dynamic-form-editor {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    padding: 10px 16px;
    border-bottom: 1px solid var(--el-border-color);

    .el-steps--simple {
      background-color: transparent;
      padding: 0;
    }
  }

  .page-body {
    flex: 1;
    overflow: auto;
  }
}

.cjui-dynamic-form-editor-base {
  padding: 30px;
}

.cjui-dynamic-form-editor-diy {
  width: 100%;
  height: 100%;
  display: flex;

  .left-board {
    width: 230px;
    height: 100%;
    overflow: auto;
  }

  .center-board {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;

    .action-bar {
      height: 40px;
      line-height: 40px;
      border-left: 1px solid var(--el-border-color-lighter);
      border-right: 1px solid var(--el-border-color-lighter);
      border-bottom: 1px solid var(--el-border-color-lighter);
      box-sizing: border-box;
      padding: 0 10px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .right-board {
    width: 320px;
    height: 100%;
    overflow: auto;

    .el-tabs {
      height: 100%;

      .el-tabs__nav.is-top {
        width: 100%;
      }

      .el-tabs__header {
        margin-bottom: 10px;
        border-bottom: 1px solid var(--el-border-color-light);
      }

      .el-tabs__nav-wrap:after {
        display: none;
      }

      .el-tabs__item {
        flex: 1;
        padding: 0;
      }

      .el-tabs__content {
        flex: 1;
        padding: 0 0 20px;
        overflow: auto;
      }

      .el-tab-pane {
        height: 100%;
      }
    }

    .el-scrollbar__view {
      height: unset;
      padding: 0 10px;
    }

    .el-collapse {
      border-top: none;
      border-bottom: none;

      .el-collapse-item__wrap {
        border-bottom: none;
        padding: 0 8px;
      }

      .el-collapse-item__header {
        background-color: #f7f8f9;
        margin-bottom: 10px;
        height: 32px;
        line-height: 32px;
        border-bottom: none;
        padding-left: 10px;
      }

      .el-collapse-item__content {
        padding-bottom: 0;
      }

      .el-slider {
        width: 95%;
      }
    }
  }
}
</style>
